﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Web;
using Admin.NET.Core;

namespace Admin.NET.Application
{
    /// <summary>
    /// 库区信息服务
    /// </summary>
    [ApiDescriptionSettings("自己的业务", Name = "WmsArea", Order = 100)]
    [Route("api/[Controller]")]
    public class WmsAreaService : IDynamicApiController, ITransient
    {
        private readonly IRepository<WmsArea, MasterDbContextLocator> _wmsAreaRep;
        private readonly IRepository<SysDictType, MasterDbContextLocator> _sysDictTypeRep;
        private readonly IRepository<SysDictData, MasterDbContextLocator> _sysDictDataRep;
        private readonly ISysExcelTemplateService _sysExcelTemplateService;
        private readonly static object _lock = new();

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="wmsAreaRep"></param>
        /// <param name="sysDictTypeRep"></param>
        /// <param name="sysDictDataRep"></param>
        /// <param name="sysExcelTemplateService"></param>
        public WmsAreaService(
            IRepository<WmsArea, MasterDbContextLocator> wmsAreaRep,
            IRepository<SysDictType, MasterDbContextLocator> sysDictTypeRep,
            IRepository<SysDictData, MasterDbContextLocator> sysDictDataRep,
            ISysExcelTemplateService sysExcelTemplateService
        )
        {
            _wmsAreaRep = wmsAreaRep;
            _sysDictTypeRep = sysDictTypeRep;
            _sysDictDataRep = sysDictDataRep;
            _sysExcelTemplateService = sysExcelTemplateService;
        }

        /// <summary>
        /// 分页查询库区信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<WmsAreaOutput>> Page([FromQuery] WmsAreaSearch input)
        {
            var wmsAreas = await _wmsAreaRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(input.AreaName), u => EF.Functions.Like(u.AreaName, $"%{input.AreaName.Trim()}%"))
                .Where(input.AreaStatus != null, u => u.AreaStatus == input.AreaStatus)
                .Where(input.AreaType != null, u => u.AreaType == input.AreaType)
                .Where(input.IsSteel != null, u => u.IsSteel == input.IsSteel)
                .Where(input.WorkShopType != null, u => u.WorkShopType == input.WorkShopType)

                .OrderBy(PageInputOrder.OrderBuilder<WmsAreaSearch>(input))
                .ProjectToType<WmsAreaOutput>()
                .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsAreas;
        }

        /// <summary>
        /// 不分页查询库区信息列表
        /// </summary>
        /// <param name="input">库区信息查询参数</param>
        /// <returns>(库区信息)实例列表</returns>
        [HttpGet("listNonPage")]
        public async Task<List<WmsAreaOutput>> ListNonPageAsync([FromQuery] WmsAreaSearchNonPage input)
        {
            var pAreaName = input.AreaName?.Trim() ?? "";
            var pAreaStatus = input.AreaStatus;
            var pAreaType = input.AreaType;
            var pIsSteel = input.IsSteel;
            var pWorkShopType = input.WorkShopType;
            var pIssueState = input.IssueState;
            var wmsAreas = await _wmsAreaRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(pAreaName), u => EF.Functions.Like(u.AreaName, $"%{pAreaName}%"))
                .Where(pAreaStatus != null, u => u.AreaStatus == pAreaStatus)
                .Where(pAreaType != null, u => u.AreaType == pAreaType)
                .Where(pIsSteel != null, u => u.IsSteel == pIsSteel)
                .Where(pWorkShopType != null, u => u.WorkShopType == pWorkShopType)

            .OrderBy(PageInputOrder.OrderNonPageBuilder(input))
            .ProjectToType<WmsAreaOutput>()
            .ToListAsync();
            return wmsAreas;
        }

        /// <summary>
        /// 增加库区信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task Add(AddWmsAreaInput input)
        {
            var wmsArea = input.Adapt<WmsArea>();
            await _wmsAreaRep.InsertAsync(wmsArea);
        }

        /// <summary>
        /// 删除库区信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task Delete(DeleteWmsAreaInput input)
        {
            var wmsArea = await _wmsAreaRep.FirstOrDefaultAsync(u => u.Id == input.Id);
            await _wmsAreaRep.DeleteAsync(wmsArea);
        }

        /// <summary>
        /// 更新库区信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task Update(UpdateWmsAreaInput input)
        {
            var isExist = await _wmsAreaRep.AnyAsync(u => u.Id == input.Id, false);
            if (!isExist) throw Oops.Oh(ErrorCode.D3000);

            var wmsArea = input.Adapt<WmsArea>();
            await _wmsAreaRep.UpdateAsync(wmsArea, ignoreNullValues: true);
        }

        /// <summary>
        /// 获取库区信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<WmsAreaOutput> Get([FromQuery] QueryeWmsAreaInput input)
        {
            return (await _wmsAreaRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id)).Adapt<WmsAreaOutput>();
        }

        /// <summary>
        /// 获取库区信息列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<List<WmsAreaOutput>> List([FromQuery] WmsAreaInput input)
        {
            return await _wmsAreaRep.DetachedEntities.ProjectToType<WmsAreaOutput>().ToListAsync();
        }

        /// <summary>
        /// 组装车间获取库区
        /// </summary>
        /// <returns></returns>
        [HttpGet("TaskWmsArea")]
        public async Task<dynamic> TaskWmsArea()
        {
            var list = await _wmsAreaRep.DetachedEntities.Where(x => x.WorkShopType == LesWorkShopType.JIAOHEBANCHEJIAN).ToListAsync();
            return list.Select(e => new { Code = e.Id, AreaName = e.AreaName });
        }

        /// <summary>
        /// 获取仓库下拉框
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAreaEntranceList")]
        public async Task<List<AreaEntranceListOutput>> GetAreaEntranceList()
        {
            var data = await _wmsAreaRep.DetachedEntities.ProjectToType<WmsAreaOutput>().ToListAsync();
            List<AreaEntranceListOutput> areaEntranceListOutputLists = new List<AreaEntranceListOutput>();
            foreach (var item in data)
            {
                AreaEntranceListOutput areaEntranceListOutputList = new AreaEntranceListOutput();
                areaEntranceListOutputList.AreaId = item.Id;
                areaEntranceListOutputList.AreaName = item.AreaName;
                areaEntranceListOutputLists.Add(areaEntranceListOutputList);
            }
            return areaEntranceListOutputLists;
        }

        ///// <summary>
        ///// 出库口下拉框
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[HttpGet("GetEntranceOutList")]
        //public async Task<List<EntranceListOutput>> GetEntranceOutList([FromQuery] EntranceOutInput input)
        //{
        //    var data = await _lesEntranceRep.DetachedEntities.Where(u => u.AreaId == input.Id && u.EntranceType == Core.LesEntranceType.CHUKU).ProjectToType<LesStationOutput>().ToListAsync();
        //    List<EntranceListOutput> entranceLists = new List<EntranceListOutput>();
        //    foreach (var item in data)
        //    {
        //        EntranceListOutput entranceList = new EntranceListOutput();
        //        entranceList.EntranceId = item.Id;
        //        entranceList.EntranceName = item.Name;
        //        entranceLists.Add(entranceList);
        //    }
        //    return entranceLists;
        //}

        /// <summary>
        /// Excel模板导入库区信息功能
        /// </summary>
        /// <param name="file">Excel模板文件</param>
        /// <param name="importExcelType">Excel导入方式</param>
        /// <returns>导入的记录数</returns>
        [HttpPost("fromExcel")]
        public async Task<int> FromExcelAsync(IFormFile file, [FromQuery] ImportExcelType importExcelType)
        {
            int size = 200;
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsArea", "v2");
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var keys = excelTemplate.UnionUniqueFields.Split(",") ?? Array.Empty<string>();
            for (var i = 0; i < keys.Length; i++)
            {
                keys[i] = keys[i]?.Trim() ?? string.Empty;
            }
            ExcelUtil.FromExcel(file, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, out List<string> headers, out List<List<object>> data, out string sheetName);
            List<WmsAreaOutput> wmsAreaList = DataConvertUtil.ToObjectList(headers, data, sheetName, keys, excelTemplate?.DataStartLine ?? 2, out Dictionary<string, WmsAreaOutput> dict);
            List<Dictionary<string, object>> uniqueKeyValueDictList = wmsAreaList.ParseUniqueKeyValueDictList(keys.ToList(), excelTemplate?.DataStartLine ?? 2, sheetName);
            var filters = DataConvertUtil.GetExpressionListByUniqueDict<WmsArea>(keys.ToList(), uniqueKeyValueDictList, size);
            var selectKeys = keys.ToList();
            if (!selectKeys.Contains("Id")) selectKeys.Add("Id");
            var selector = DataConvertUtil.GetSelectExpressionListByUniqueDict<WmsArea, WmsAreaOutput>(selectKeys);
            List<WmsArea> updates = new();
            List<WmsArea> adds = new();

            lock (_lock)
            {
                foreach (var filter in filters)
                {
                    var wmsAreaExistSubList = _wmsAreaRep.Where(filter).Select(selector).ToList();
                    wmsAreaExistSubList.ForEach(x =>
                    {
                        var k = DataConvertUtil.GetKey(x, keys);
                        if (dict.ContainsKey(k)) dict[k].Id = x.Id;
                    });
                }

                foreach (var wmsArea in wmsAreaList)
                {
                    if (wmsArea.Id > 0)
                    {
                        if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.Add(wmsArea.Adapt<WmsArea>());
                    }
                    else
                    {
                        adds.Add(wmsArea.Adapt<WmsArea>());
                    }
                }

                if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.ForEach(x => _wmsAreaRep.Update(x));

                var maxId = _wmsAreaRep.DetachedEntities.OrderByDescending(x => x.Id).Select(x => x.Id).FirstOrDefault();
                adds.ForEach(x => x.Id = ++maxId);
                Db.GetDbContext().Set<WmsArea>().AddRange(adds);
                Db.GetDbContext().SaveChanges();
            }

            await Task.CompletedTask;
            return adds.Count;
        }

        /// <summary>
        /// 根据版本下载库区信息的Excel导入模板
        /// </summary>
        /// <param name="version">模板版本</param>
        /// <returns>下载的模板文件</returns>
        [HttpGet("downloadExcelTemplate")]
        public async Task<IActionResult> DownloadExcelTemplate([FromQuery] string version)
        {
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsArea", version);
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var path = Path.Combine(@"\", excelTemplate.TemplateFileName);
            Stream ms = FileUtil.Download(path, excelTemplate.TemplateFileName);
            var fileName = HttpUtility.UrlEncode($"{excelTemplate.Name}导入模板.xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }

        /// <summary>
        /// 根据库区信息查询参数导出Excel
        /// </summary>
        /// <param name="input">库区信息查询参数</param>
        /// <returns>导出的Excel文件</returns>
        [HttpGet("toExcel")]
        public async Task<IActionResult> ToExcelAsync([FromQuery] WmsAreaSearchNonPage input)
        {
            var wmsAreaList = await ListNonPageAsync(input);
            MemoryStream ms = new();
            DataConvertUtil.ToExcelData(wmsAreaList, _sysDictTypeRep, _sysDictDataRep, out List<string> headers,
                out List<List<object>> data, out string sheetName);
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsArea", "v1");
            if (excelTemplate != null)
            {
                ExcelUtil.ToExcel(excelTemplate.TemplateFileName, headers, data, sheetName, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, ms);
            }
            else
            {
                ExcelUtil.ToExcel(headers, data, sheetName, ms);
            }
            ms.Position = 0;
            var fileName = HttpUtility.UrlEncode($"{sheetName}[{DateTimeOffset.Now:yyyy-MM-dd}].xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
    }
}
